package com.shse.sale.web.controller;

import com.shse.sale.meta.User;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by shse on 4/11/2016.
 */
@Controller
public class UploadController {

    /**
     * 图片上传
     *
     * @return
     */
    @RequestMapping("/upload/uploadPic")
    public String uploadPic(HttpSession session,
                            HttpServletRequest request,
                            ModelMap map,
                            @RequestParam(value = "image", required = false) MultipartFile image) {

        User user = (User) session.getAttribute("user");

        //如果用户条件符合且图片存在
        if (user != null && user.getUsertype() == 1 && null != image && image.getSize() > 0) {

            //如果图片格式符合
            String fileType = image.getContentType();
            if (fileType.equals("image/gif") || fileType.equals("image/png") || fileType.equals("image/jpeg")) {

                String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(image.getOriginalFilename());
                if (!fileName.equalsIgnoreCase("")) {
                    try {

                        //写入图片
                        String filePath = request.getServletContext().getRealPath("/") + File.separator + "upload" + File.separator + fileName;
                        File f = new File(filePath);
                        image.transferTo(f);

                        //上传图片成功后开始构建json所需map
                        map.addAttribute("path", "/upload/" + fileName);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "json";
    }
}
